import React, { Component } from "react";

import FilterTitle from '../FilterTitle'
import FilterPicker from '../FilterPicker'
import FilterMore from '../FilterMore'

import { API } from "../../../../utils/api";

// 导入spring组件
import { Spring, animated } from 'react-spring'

import styles from './index.module.css'

// FilterTitle中标题高亮状态
const titleSelectedStatus = {
  area: false,
  rentType: false,
  price: false,
  more: false
}

const selectedValues = {
  area: ['area', 'null'],
  rentType: ['null'],
  price: ['null'],
  more: []
}

export default class Filter extends Component {
  constructor(props) {
    super(props)
    this.state = {
      // 控制组件展示类型
      type: '',
      // 选中状态
      titleSelectedStatus,
      // filter数据
      filterData: [],
      // filter默认值及选中值
      selectedValues
    }
  }

  // 获取封装所有筛选条件的方法
  async getFiltersData() {
    // 获取当前定位城市id
    if (localStorage.getItem('hkzf_city')) {
      var { value } = JSON.parse(localStorage.getItem('hkzf_city'))
    } else {
      value = 'AREA|88cff55c-aaa4-e2e0'
    }
    let res = await API.get(`/houses/condition?id=${value}`)

    this.setState({
      filterData: res.data.body
    })

  }

  // 判断当前标题对应的表单项是否不为空
  judgeTitleStatus(type, value) {
    if (!value) {
      value = this.state.selectedValues[type]
    }
    switch (type) {
      case 'area':
        if ( value[1] !== 'null' ) {
          return true
        } else {
          return false
        }
      case 'rentType':
        if ( value[0] !== 'null' ) {
          return true
        } else {
          return false
        }
      case 'price':
        if ( value[0] !== 'null' ) {
          return true
        } else {
          return false
        }
      case 'more':
        if (value.length) {
          return true
        } else {
          return false
        }
      default:
        break;
    }
  }

  // 返回当前所选筛选条件给父组件
  sendHouseSearchParams() {
    const { selectedValues } = this.state
    let params = {}

    Object.keys(selectedValues).forEach(type => {
      let tempData = selectedValues[type]
      if (type === 'area') {
        for (let i = tempData.length-1; i> -1; i--) {
          if (tempData[i] !== 'null' && i > 0) {
            params[tempData[0]] = tempData[i]
            break
          }
        }
      } else if (type === 'rentType' && tempData[0] !== 'null') {
        params[type] = tempData[0]
      } else if (type === 'price' && tempData[0] !== 'null') {
        params[type] = tempData[0].split('|')[1]
      } else if (type === 'more' && tempData.length) {
        params[type] = tempData.join(',')
      }
    })
    this.props.getSelectedValues(params)
  }

  onTitleChange = (type) => {
    // 给body添加样式
    this.htmlBody.className = "body-fixed"
    const { titleSelectedStatus } = this.state
    let newTitleSelectedStatus = {...titleSelectedStatus}

    Object.keys(titleSelectedStatus).map(key => {
      if (key !== type) {
        newTitleSelectedStatus[key] = this.judgeTitleStatus(key)
      } else {
        newTitleSelectedStatus[key] = true
      }
      return null
    })
    this.setState(prevState => {
      return {
        // titleSelectedStatus: {
        //   // 获取当前对象中所有属性值
        //   ...prevState.titleSelectedStatus,
        //   // 覆盖前面展开的同名属性值
        //   [type]: true,
        // },
        titleSelectedStatus: newTitleSelectedStatus,
        type
      }
    })
  }

  // 取消(隐藏对话框)
  onCancel = (type) => {
    // 给body去除样式
    this.htmlBody.className = ""
    let status = this.judgeTitleStatus(type)
    this.setState({
      type: '',
      titleSelectedStatus: {
        ...this.state.titleSelectedStatus,
        [type]: status
      }
    })
  }

  // 确定
  onSave = (type, value) => {
    // 给body去除样式
    this.htmlBody.className = ""
    let status = this.judgeTitleStatus(type, value)
    this.setState({
      type: '',
      selectedValues: {
        ...this.state.selectedValues,
        [type]: value
      },
      titleSelectedStatus: {
        ...this.state.titleSelectedStatus,
        [type]: status
      }
    }, this.sendHouseSearchParams)
  }

  // 渲染FilterPicker组件
  renderFilterPicker() {
    const { filterData: { area, subway, rentType, price }, type, selectedValues } = this.state
    let selectedValue = selectedValues[type]

    // 根据type值返回数据
    let data = [], cols = 1
    switch(type) {
      case 'area':
        data = [area, subway]
        cols = 3
        break;
      case 'rentType':
        data = rentType
        cols = 1
        break;
      case 'price':
        data = price
        cols = 1
        break;
      default:
        break;
    }

    if (type === 'area' || type === 'rentType' || type === 'price') {
      // 利用react key值不同会生成不同组件的特性，在进行key值切换的时候重新生成组件 重新初始化FilterPicker组件的state 防止出现在两个type切换过程中 value值不能记录的问题
      return <FilterPicker key={type} filterData={data} cols={cols} value={selectedValue} type={type} onCancel={this.onCancel} onSave={this.onSave}/>
    } else {
      return null
    }
  }

  renderFilterMore() {
    const { type, selectedValues, filterData: {characteristic, floor, oriented, roomType} } = this.state
    if (type !== 'more' ) {
      return null
    } else {
      return <FilterMore selectedValues={selectedValues} type={type} onSave={this.onSave} onCancel={this.onCancel} characteristic={characteristic} floor={floor} oriented={oriented} roomType={roomType} /> 
    }
  }

  renderMask() {
    const { type } = this.state
    const isHide = (type === '')

    return (
      <Spring from={{ opacity: 0 }} to={{ opacity: isHide ? 0 : 1 }}>
        {
          // style是opacity从0到1变化的中间值
          style => {
            if (isHide) return null
            return <animated.div style={style} className={[styles.mask, type === 'more' ? styles.moreMask : ''].join(' ')} onClick={() => this.onCancel(type)}></animated.div>
          }
        }
      </Spring>
    )
  }

  componentDidMount() {
    // 获取body
    this.htmlBody = document.body
    this.getFiltersData()
  }

  render() {
    return (
      <div className={styles.root}>
        <div className={styles.content}>
          {/* 标题栏 */}
          <FilterTitle titleSelectedStatus={this.state.titleSelectedStatus} clickFn={this.onTitleChange}/>
          {/* 前三个菜单对应的内容 */}
          {
            this.renderFilterPicker()
          }
          
          {/* 最后一个菜单对应的内容 */}
          {
            this.renderFilterMore()
          }
        </div>
        {/* 遮罩层 */}
        {
          this.renderMask()
        }
      </div>
    )
  }
}